package com.xiaohai.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaohai.common.R;
import com.xiaohai.projo.Teacher;
import com.xiaohai.service.TeacherService;
import com.xiaohai.utils.ToPinyinUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xiaohai
 * @since 2024-01-22
 */
@Slf4j
@RestController
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;



    @GetMapping("/list")
    public R<Page<Teacher>> list(Integer currentPage, Integer pageSize, Teacher teacher) {
        Page<Teacher> list = teacherService.myList(currentPage, pageSize, teacher);
        return R.success(list, "获取数据成功");
    }

    @PostMapping
    public R<Objects> addAndUpdate(@RequestBody Teacher teacher) {
        log.info("teacher:{}", teacher);
        Integer id = teacher.getId();
        if (id != null) { // 修改
            Boolean b = teacherService.myUpdate(teacher);
            if (b) {
                return R.success(null, "修改成功");
            }
            return R.error("修改失败", 201);
        } else {
            String account = ToPinyinUtil.toPinyin(teacher.getName());
            teacher.setAccount(account);
            String s = DigestUtils.md5DigestAsHex("123456".getBytes());
            teacher.setPassword(s);
            boolean add = teacherService.add(teacher);
            if (add) {
                return R.success(null, "新增成功");
            }
            return R.error("新增失败", 201);
        }
    }

    @GetMapping
    public R<Teacher> detail(String id) {
        Teacher teacher = teacherService.detail(id);
        if (Objects.isNull(teacher)) {
            return R.error("获取详情失败", 201);
        }
        return R.success(teacher, "获取详情成功");
    }

    @DeleteMapping
    public R<Object> deleteById(Integer id) {
        log.info("id:{}", id);

        boolean b = teacherService.delete(id);
        if(b){
            return R.success(null,"删除成功");
        }

        return R.error("删除失败,该教师是班主任或者正在授课", 201);
    }
}
